<template>
  <div style="display: flex;flex-direction: column;height: 100vh;">
	  <div class="header" v-if="showHeader">
	  	<div class="search" @click="searchClick">
	  		<van-icon name="search" />
	  		搜索
	  	</div>
	  	<div class="date" @click="showPicker = true">
	  		{{ year }}年 {{ month }}月 第{{ weekOfMonth }}周
	  		<van-icon name="arrow-down" />
	  	</div>
	  </div>
	  <div class="header" v-else>
	  	<van-search
	  		style="width: 100%"
	  		v-model="searchVal"
	  		background="#eee"
	  		placeholder="搜索考勤组中的成员或部门名称"
	  		@search="onSearch"
	  		@cancel="onCancel"
	  	/>
	  	<div style="width: 50px" @click="onSearch">搜索</div>
	  	<div style="width: 50px" @click="onCancel">取消</div>
	  </div>
	  
	  <div class="table">
	  	<div class="th">
	  		<div
	  			v-for="(date, week) in weekDates"
	  			class="td"
	  			:class="{
	  				today: isToDay(date),
	  				active: selectBox?.i == -1 && selectBox?.j == week,
	  			}"
	  			@click="select(-1, week)"
	  		>
	  			<div class="week">{{ weekName[week] }}</div>
	  			<div class="date" :class="{ toMonth: isToMonth(date) }">
	  				<template v-if="isToDay(date)"> 今 </template>
	  				<template v-else>
	  					{{ date.getDate() }}
	  				</template>
	  			</div>
	  		</div>
	  	</div>
	  	<div class="tr" v-for="(item, i) in datas">
	  		<div
	  			class="td name"
	  			:class="{ active: i == selectBox?.i && selectBox.j == -1 }"
	  			@click="select(i, -1)"
	  		>
	  			{{ item.name }}
	  		</div>
	  		<div
	  			class="td"
	  			v-for="(w, j) in item.work"
	  			@click="select(i, j)"
	  			:class="{ select: isSelect(i, j) }"
	  		>
	  			<div v-if="w.type == '-999'"></div>
	  			<div v-else-if="w.type == '-1'">休</div>
	  			<div class="name" v-else :style="{ background: getColor(w.type) }">
	  				{{ shiftMap.get(w.type)?.substring(0, 4) }}
	  			</div>
	  			<div v-if="w.edit == true" class="edited"></div>
	  		</div>
	  	</div>
	  </div>
	  <van-pagination
	  	v-model="pageIndex"
	  	mode="simple"
	  	:total-items="count"
	  	:items-per-page="8"
	  	@change="pageChange"
	  />
	  
	  <div class="save">
	  	<van-button type="primary" block :loading="saveLoading" @click="save"
	  		>保存排班</van-button
	  	>
	  </div>
	  
	  <van-popup v-model:show="showPicker" position="bottom">
	  	<van-picker
	  		v-model="pickerSelectedValues"
	  		@cancel="pickerCancel"
	  		@confirm="pickerConfirm"
	  		:columns="columns"
	  	/>
	  </van-popup>
	  
	  <van-popup
	  	v-model:show="showButton"
	  	position="bottom"
	  	:style="{ height: '350px', overflow: 'hidden' }"
	  >
	  	<div class="bottom-popup">
	  		<a class="confirm" @click="showButton = false">确定</a>
	  		<van-tabs :active="0" shrink>
	  			<van-tab title="排班">
	  				<div style="height: 300px; overflow: auto">
	  					<div class="button-group">
	  						<div class="button" @click="takeTimeOff">
	  							<van-icon name="smile-o" /> 排休
	  						</div>
	  						<div class="button" @click="clear">
	  							<van-icon name="close" /> 清除
	  						</div>
	  					</div>
	  					<div class="list" v-for="item in shiftList" @click="schedule(item)">
	  						<div class="point"></div>
	  						{{ item.name }}
	  					</div>
	  				</div>
	  			</van-tab>
	  		</van-tabs>
	  	</div>
	  </van-popup>
  </div>
</template>
<script lang="ts" setup>
import { onMounted, ref, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import {
	showSuccessToast,
	showFailToast,
	showLoadingToast,
	closeToast,
} from 'vant'
import { showNotify } from 'vant'
import dayjs from 'dayjs'
import {
	getMonthWeek,
	getWeeks,
	getWeekDates,
	isToDay,
	isToMonth,
} from '@/util/DateUtil'

let groupId: number
const pageIndex = ref(1)
const pageSize = ref(8)
const count = ref(0)
const searchVal = ref('')
const showHeader = ref(true)
const getColor = (id) => {
	switch (id) {
		case '8':
			return 'rgb(71, 169, 252)'
		case '10':
			return 'rgb(112, 192, 111)'
		case '22':
			return 'rgb(71, 169, 252)'
		case '23':
			return 'rgb(112, 192, 111)'
		case '25':
			return 'rgb(246, 214, 92)'
		case '27':
			return 'rgb(234, 116, 77)'
		case '28':
			return 'rgb(78, 188, 204)'
		case '36':
			return 'rgb(234, 92, 133)'
		case '37':
			return 'rgb(143, 114, 242)'
		case '38':
			return 'rgb(114, 151, 242)'
		case '39':
			return 'rgb(202, 77, 228'
		case '40':
			return 'rgb(167, 204, 98)'
		default:
			return 'rgb(238, 238, 238)'
	}
}

onMounted(() => {
	pickerInit()
	groupId = Number(route.query['id'])
	getData()
})
const shiftList = ref<
	{
		name: string
		id: string
	}[]
>([])
const shiftMap = new Map()
type Work = {
	date: string
	id: string
	type: string
	edit?: boolean
}
type Data = {
	resourceid: string
	name: string
	department: string
	work: Work[]
}

const datas = ref<
	{
		resourceid: string
		name: string
		department: string
		work: {
			date: string
			id: string
			type: string
			edit?: boolean
		}[]
	}[]
>([])

//搜索
const searchClick = () => {
	pageIndex.value = 1
	pageSize.value = 8
	showHeader.value = false
}
const onSearch = () => {
	getData()
}
const onCancel = () => {
	searchVal.value = ''
	showHeader.value = true
}

const getData = async () => {
	showLoadingToast({
		duration: 0,
		message: '加载中...',
		forbidClick: true,
	})
	try {
		const startDate = dayjs(weekDates.value[0]).format('YYYY-MM-DD')
		const response = await fetch(
			`/mobile/heo/PaiBan.jsp?groupId=${groupId}&startDate=${startDate}&pageIndex=${pageIndex.value}&pageSize=${pageSize.value}&search=${searchVal.value}`
		)
		const json = await response.json()
		const data = json.data
		shiftList.value = data.shiftList
		shiftMap.clear()
		shiftList.value.forEach((e) => {
			shiftMap.set(e.id, e.name)
		})
		datas.value = data.datas
		count.value = data.count
		pageIndex.value = data.pageindex
	} catch (err) {
		console.error(err)
		showFailToast('加载失败')
	} finally {
		closeToast()
	}
}

const getEditedDatas = () => {
	let editDatas: Data[] = []
	for (let i = 0; i < datas.value.length; i++) {
		let data = datas.value[i]
		let editWork: Work[] = []
		for (let j = 0; j < data.work.length; j++) {
			let w = data.work[j]
			if (w.edit == true) {
				let ew = {
					...w,
				}
				delete ew.edit
				editWork.push(ew)
			}
		}
		if (editWork.length > 0) {
			editDatas.push({
				...data,
				work: editWork,
			})
		}
	}
	return editDatas
}
const saveLoading = ref(false)
const save = async () => {
	let editDatas = getEditedDatas()
	console.log(editDatas)
	if (editDatas.length > 0) {
		saveLoading.value = true
		try {
			await fetch('/mobile/heo/save.jsp', {
				method: 'POST',
				body: JSON.stringify({
					groupId: groupId,
					datas: editDatas,
				}),
			})
				.then((reps) => reps.json())
				.then((result) => {
					if (result.ret == '0') {
						showSuccessToast('保存成功')
						getData()
					} else {
						console.error(result)
						showFailToast('保存失败')
					}
				})
		} catch (e) {
			showFailToast('网络异常')
		} finally {
			saveLoading.value = false
		}
	} else {
		showNotify('未做任何修改')
	}
}
const pageChange = () => {
	// 如果有未保存的内容，不可以跳转到下一页
	getData()
}

const route = useRoute()
const router = useRouter()

const now = new Date()
const year = ref(now.getFullYear())
const month = ref(now.getMonth() + 1)
const weekOfMonth = ref(
	getMonthWeek(now.getFullYear(), now.getMonth() + 1, now.getDate())
)

const weekName = ['一', '二', '三', '四', '五', '六', '日']
const weekDates = computed(() => {
	return getWeekDates(year.value, month.value, weekOfMonth.value)
})

const pickerSelectedValues = ref<number[]>([])
type PickerColumn = {
	text: string
	value: number
	children?: PickerColumn[]
}

const columns: PickerColumn[] = []

const pickerInit = () => {
	pickerSelectedValues.value = [year.value, month.value, weekOfMonth.value]
	for (let y = year.value - 1; y <= year.value + 1; y++) {
		let c1: PickerColumn[] = []
		for (let m = 1; m <= 12; m++) {
			let c2: PickerColumn[] = []
			for (let w = 1; w <= getWeeks(y, m); w++) {
				c2.push({ text: `第${w}周`, value: w })
			}
			c1.push({ text: m + '月', value: m, children: c2 })
		}
		columns.push({ text: y + '年', value: y, children: c1 })
	}
}

const pickerCancel = () => {
	showPicker.value = false
	pickerSelectedValues.value = [year.value, month.value, weekOfMonth.value]
}

const pickerConfirm = () => {
	year.value = pickerSelectedValues.value[0]
	month.value = pickerSelectedValues.value[1]
	weekOfMonth.value = pickerSelectedValues.value[2]
	getData()
	showPicker.value = false
}

const back = () => {
	router.back()
}

const selectBox = ref<{
	i: number
	j: number
}>()

const select = (i: number, j: number) => {
	selectBox.value = {
		i,
		j,
	}
	showButton.value = true
}

const showButton = ref(false)

const isSelect = (i: number, j: number) => {
	return (
		selectBox.value &&
		(selectBox.value.i == i || selectBox.value.i == -1) &&
		(selectBox.value.j == j || selectBox.value.j == -1)
	)
}

/**
 * 休息
 */
const takeTimeOff = () => {
	getSelectIndex().forEach((e) => {
		let data = datas.value[e.i].work[e.j]
		if (data.type != '-1') {
			data.type = '-1'
			data.edit = true
		}
	})
	selectNext()
}
const clear = () => {
	getSelectIndex().forEach((e) => {
		let data = datas.value[e.i].work[e.j]
		if (data.type != '-999') {
			data.type = '-999'
			data.edit = true
		}
	})
	selectNext()
}

const schedule = (item: any) => {
	getSelectIndex().forEach((e) => {
		let data = datas.value[e.i].work[e.j]
		if (data.type != item.id) {
			data.type = item.id
			data.edit = true
		}
	})
	selectNext()
}

const selectNext = () => {
	if (selectBox.value) {
		if (selectBox.value.j >= 0 && selectBox.value.j < 6) {
			selectBox.value.j += 1
		}
	}
}

const getSelectIndex = (): { i: number; j: number }[] => {
	if (!selectBox.value) {
		return []
	}
	if (selectBox.value.i != -1 && selectBox.value.j != -1) {
		return [
			{
				i: selectBox.value.i,
				j: selectBox.value.j,
			},
		]
	} else if (selectBox.value.i == -1) {
		let array = []
		for (let i = 0; i < datas.value.length; i++) {
			array.push({
				i: i,
				j: selectBox.value.j,
			})
		}
		return array
	} else {
		let array = []
		for (let j = 0; j < 7; j++) {
			array.push({
				i: selectBox.value.i,
				j: j,
			})
		}
		return array
	}
}

const showPicker = ref(false)
</script>

<style   scoped>
.header {
  height: 50px;
  color: #878889;
  display: flex;
  align-items: center;
  font-size: 16px;
  font-weight: 300;
}
.header .search {
  padding: 0px 15px;
  border-right: 1px solid #9c9c9c;
}
.header .date {
  margin-left: 15px;
}
.table {
  background: #fff;
  border-top-left-radius: 10px;
  border-top-right-radius: 10px;
  flex: 1;
  font-size: 12px;
}
.table .th {
  height: 80px;
  display: flex;
  align-items: center;
  border-bottom: 1px solid #eee;
  justify-content: flex-end;
}
.table .th .td {
  text-align: center;
  color: #9c9c9c;
  width: 45px;
  height: 70px;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  justify-content: center;
}
.table .th .td .date {
  margin-top: 5px;
  height: 18px;
  line-height: 18px;
}
.table .th .td .toMonth {
  color: #000;
}
.table .th .today {
  background-color: #e7effc;
}
.table .th .today .date {
  color: #1989fa !important;
  font-weight: 700;
  font-size: 16px;
}
.table .th .active {
  background-color: #1989fa;
}
.table .tr {
  display: flex;
  align-items: center;
  border-bottom: 1.5px solid #eee;
  height: 45px;
  box-sizing: border-box;
}
.table .tr .td {
  display: flex;
  width: 45px;
  height: 45px;
  align-items: center;
  justify-content: center;
  color: #666;
  border-right: 1px solid #efefef;
  flex: 0 0 45px;
  box-sizing: border-box;
}
.table .tr .td .name {
  flex: 0 0 40px;
  background-color: #efefef;
  width: 40px;
  height: 40px;
  line-height: 16px;
  padding: 4px;
  box-sizing: border-box;
  border-radius: 5px;
  color: #fff;
}
.table .tr .select {
  border: 1px solid #1989fa !important;
}
.table .tr .name {
  flex: 1;
  text-align: center;
}
.table .tr .active {
  color: #1989fa !important;
}
.edited {
  position: absolute;
  width: 0px;
  height: 0px;
  border-left: 10px solid transparent;
  border-bottom: 10px solid #1989fa;
  bottom: 0px;
  right: 0px;
}
.bottom-popup .confirm {
  position: absolute;
  height: 44px;
  line-height: 44px;
  top: 0px;
  right: 0px;
  padding: 0px 16px;
  z-index: 999;
  color: #1989fa;
  font-size: 14px;
}
.bottom-popup .button-group {
  display: flex;
  border: 1px solid #efefef;
  margin: 16px 16px 0px 16px;
  border-radius: 8px;
  height: 60px;
}
.bottom-popup .button-group .button {
  flex: 1;
  text-align: center;
  height: 100%;
  line-height: 60px;
  font-size: 18px;
}
.bottom-popup .button-group .button:first-child {
  border-right: 1px solid #efefef;
}
.bottom-popup .list {
  border: 1px solid #efefef;
  margin: 10px 16px 10px 16px;
  border-radius: 8px;
  height: 60px;
  line-height: 60px;
  padding: 0px 30px;
  position: relative;
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
}
.bottom-popup .list .point {
  content: '';
  display: block;
  position: absolute;
  width: 6px;
  height: 6px;
  background-color: #a0987e;
  border-radius: 50%;
  top: 27px;
  left: 15px;
}
.save {
  padding: 15px;
  background: #fff;
  border-top: 1px solid #efefef;
}

</style>
